package yxy.game.pm2.command.player;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.playerCommand.PlayerCommandHandler;
import yxy.game.pm2.module.playerCommand.PlayerCommandModule;
import yxy.game.pm2.module.playtype.PlayTypeHandle;
import yxy.game.pm2.module.playtype.PlayTypeModule;

import java.util.List;

/**
 * @author wrs
 * @since 2022-08-04
 * @descrition 玩家点数消耗
 * */
@MessageType(proto = Command.PlayerPointCost, classtype = PlayerMessage.PlayerPointCostRequest.class)
public class CMD_PlayerPointCost extends Command<PlayerMessage.PlayerPointCostRequest> {

    @Override
    public void execute(MessageSource messageSource, PlayerMessage.PlayerPointCostRequest request) throws Exception {
        String playerCode = messageSource.getTag();
        List<Integer> propertyLevelList = request.getPropertyLevelList(); //攻防血属性点数  【攻击、防御、生命】

        PlayerMessage.PlayerPointCostResponse.Builder response = PlayerMessage.PlayerPointCostResponse.newBuilder();

        PlayerCommandHandler handler = new PlayerCommandHandler();
        try {
            PlayerCommandModule playerCommandModule = PlayerCommandModule.get(playerCode);
            if (playerCommandModule == null){
                send(messageSource,response, Result.DataError);
            }
            //todo 检查最高级不能超过最低级 5%
            Result checkResult = handler.checkProperty(propertyLevelList,playerCommandModule);
            if (!checkResult.equals(Result.Success)){
                response.setSurplusPoint(playerCommandModule.getPoint());
                send(messageSource,response,checkResult);
                return;
            }

            //todo 属性加点
            Result res = handler.costPointToUpgrade(propertyLevelList,playerCommandModule,playerCode);
            if (!res.equals(Result.Success)){
                response.setSurplusPoint(playerCommandModule.getPoint());
                send(messageSource,response,res);
            }

            Result result = handler.packPointCostInfo(playerCommandModule,response);

            send(messageSource,response,result);

            PlayTypeModule playTypeModule = PlayTypeModule.get(playerCode);
            PlayTypeHandle.savePlayerCommand(playerCode,playTypeModule);
            new BattleHandle().powerUpdate(playerCode); //战力更新
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private void send(MessageSource messageSource, PlayerMessage.PlayerPointCostResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}
